package demo.servlet;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import demo.output.CodeMessage;
import demo.util.CodeMessageUtil;

/**
 * Servlet implementation class CheckGitUserHomeServlet
 */
@WebServlet("/CheckGitUserHomeServlet")
public class CheckGitUserHomeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CheckGitUserHomeServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
//		response.getWriter().append("Served at: ").append(request.getContextPath());
		String url = request.getParameter("url");
		CodeMessage cm = new CodeMessage();
		if(url == null || "".equals(url.trim())) {
			cm.setCode(CodeMessageUtil.CD_400);
			cm.setMessage("url 参数为空.");
		} else {
			url = url.trim();
			try {
				URL u = new URL(url);
				HttpURLConnection conn = (HttpURLConnection)u.openConnection();
				conn.connect();
				int ret = conn.getResponseCode();
				if (ret == HttpURLConnection.HTTP_OK) {
					cm.setCode(CodeMessageUtil.CD_200);
					cm.setMessage("OK");
				} else {
					cm.setCode(CodeMessageUtil.CD_500);
					cm.setMessage("url " + url + " connect: " + ret);
				}
				conn.disconnect();
			} catch (Exception e) {
				cm.setCode(CodeMessageUtil.CD_501);
				cm.setMessage(e.getMessage());
			}
		}
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json");
		response.getWriter().print(cm.toJson());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
